package jgl.vajra.management.manager;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.orhanobut.logger.Logger;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.management.bean.AddressBean;
import jgl.vajra.management.widget.manager.RxJavaHttpManager;
import jgl.vajra.management.widget.manager.SPManager;
import jgl.vajra.management.widget.manager.retrofit.RetrofitJsonManager;
import jgl.vajra.management.widget.permissions.PermissionListener;
import jgl.vajra.management.widget.permissions.PermissionsUtil;
import jgl.vajra.management.widget.retrofithelper.rxsubscriber.ProgressObserver;
import jgl.vajra.management.widget.utils.ToastUtils;
import jgl.vajra.management.widget.utils.UIUtils;

public class BaiduPositioningManager {

    private LocationClient mLocationClient;

    private static class BaiduPositioningManagerSingleton {
        private static final BaiduPositioningManager INSTANCE = new BaiduPositioningManager();

    }

    public static BaiduPositioningManager getInstance() {
        return BaiduPositioningManagerSingleton.INSTANCE;
    }

    private BaiduPositioningManager() {
    }

    public void initLocation(Context context) {

        String[] permissions = {
                Manifest.permission.ACCESS_FINE_LOCATION,

        };
        PermissionsUtil.requestPermission(context, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        initLocationManager(context);
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        //  ToastUtils.showShort("请到设置-权限管理中开启");
                        AddressBean data = new AddressBean();
                        data.countryName = "中国";
                        data.countryCode = "0";
                        data.adminArea = "北京市";
                        data.locality = "北京市";
                        data.subLocality = "东城区";
                        data.featureName = "";
                        data.latitude = 39.915119;
                        data.longitude = 116.403963;
                        SPManager.HomeData.saveAddressData(data);
                    }
                }, permissions, false, null
        );

    }

    private class MyBDLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // 非空判断
            if (location != null) {
                // 根据BDLocation 对象获得经纬度以及详细地址信息
              /*  double latitude = location.getLatitude();
                double longitude = location.getLongitude();
                String address = location.getAddrStr();*/


                String countryName = location.getCountry();//国家
                String countryCode = location.getCountryCode();
                String adminArea = location.getProvince();//省
                String locality = location.getCity();//市
                String subLocality = location.getDistrict();//区
                String featureName = location.getStreet();//街道
                double latitudeAddress = location.getLatitude();
                double longitudeAddress = location.getLongitude();

                AddressBean data = new AddressBean();
                data.countryName = countryName;
                data.countryCode = countryCode;
                data.adminArea = adminArea;
                data.locality = locality;
                data.subLocality = subLocality;
                data.featureName = featureName;
                data.latitude = latitudeAddress;
                data.longitude = longitudeAddress;

                SPManager.HomeData.saveAddressData(data);

                Logger.d(longitudeAddress+"countryName" + countryName + "countryCode" + countryCode + "adminArea" + adminArea
                        + "locality" + locality + "subLocality" + subLocality + "featureName" + featureName+latitudeAddress);

                uploadLocationInfo(location);

                if (mLocationClient.isStarted()) {
                    // 获得位置之后停止定位
                    mLocationClient.stop();
                }
            }
        }

    }

    private void initLocationManager(Context context) {
        // 声明LocationClient类
        mLocationClient = new LocationClient(context);
        MyBDLocationListener mBDLocationListener = new MyBDLocationListener();
        // 注册监听
        mLocationClient.registerLocationListener(mBDLocationListener);

        //使用定位管理者获取定位坐标
        LocationManager systemService = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = systemService.getProviders(true);
        String provider = "";
        for (int i = 0; i < providers.size(); i++) {
            if (providers.contains(LocationManager.GPS_PROVIDER)) {
                provider = LocationManager.GPS_PROVIDER;
            } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                provider = LocationManager.NETWORK_PROVIDER;
            } else {
                ToastUtils.showShort("定位失败!");
            }
        }
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        if (TextUtils.isEmpty(provider)) {
            ToastUtils.showShort("检查权限是否开启!");
        }else {
            // 声明定位参数
            LocationClientOption option = new LocationClientOption();
            option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);// 设置定位模式 高精度
            option.setCoorType("bd09ll");// 设置返回定位结果是百度经纬度 默认gcj02
            option.setScanSpan(5000);// 设置发起定位请求的时间间隔 单位ms
            option.setIsNeedAddress(true);// 设置定位结果包含地址信息
            option.setNeedDeviceDirect(true);// 设置定位结果包含手机机头 的方向
            // 设置定位参数
            mLocationClient.setLocOption(option);
            // 启动定位
            mLocationClient.start();
        }
    }

    private void uploadLocationInfo(BDLocation location) {
        Logger.d("uploadLocationInfo"+ (location==null));
        if (location == null) return;
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization);
        map.put("city", URLEncoder.encode(location.getCity()));
        RetrofitJsonManager.getInstance().getApiService().modifyInformation(map).compose(RxJavaHttpManager.applyTransformer()).subscribe(new ProgressObserver<Object>(false,null) {
            @Override
            public void _onNext(Object o) {

            }
        });
    }
}
